package com.bw.home.model.service

import androidx.lifecycle.viewModelScope
import com.bw.home.R
import com.bw.home.intent.SimpleVideoKeywordIntent
import com.bw.home.model.api.SimpleVideoApi
import com.bw.home.state.SimpleVideoKeywordState
import com.bw.mvicore.model.BaseModel
import com.bw.net.RetrofitUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

/**
 * @author:created by hahajing
 * 时间：2024/4/29 0029
 * 企鹅号:444511958
 * 描述:
 */
class SimpleVideoKeywordModel:BaseModel<SimpleVideoKeywordIntent>() {
    private val api: SimpleVideoApi by lazy {
        RetrofitUtils.create(SimpleVideoApi::class.java)
    }

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {
                    is SimpleVideoKeywordIntent.GetSimpleVideoByKeywordIntent -> {
                        getSimpleDataByKeyword(it.keyword,it.page, it.pageSize)
                    }
                }
            }
        }
    }

    private val _state: MutableStateFlow<SimpleVideoKeywordState> = MutableStateFlow(SimpleVideoKeywordState.SimpleVideoKeywordDefaultState)
    val state: MutableStateFlow<SimpleVideoKeywordState>
        get() = _state

    private fun getSimpleDataByKeyword(keyword:String,page: Int, pageSize: Int) {
        viewModelScope.launch {
            val result = api.getSimpleVideoByKeyword(keyword,page, pageSize)
            if (result.code == 0) {
                state.value= SimpleVideoKeywordState.SimpleVideoKeywordSuccess(result.data)
            } else {
                state.value= SimpleVideoKeywordState.SimpleVideoKeywordFailed(Throwable(R.string.simplevideo_getvideodata_failed.toString()))
            }
        }
    }
}